<?php

namespace api\modules\user\models;

use common\helpers\IpHelper;
use common\models\user\UserSignin;

class SigninForm extends BaseModel {

    public function rules() {
        return [
        ];
    }

    /**
     * 签到
     * @param array $params
     * @return void
     */
    public function signin($params = []) {
        if (count($params) > 0 && !$this->load($params, '')) {
            parent::throwError('参数非法', $this->getFirstErrors());
        }

        if (!$this->validate()) {
            parent::throwError('提交失败', $this->getFirstErrors());
        }

        $sign = UserSignin::find()->where(['user_id' => $this->_token->user_id])->orderBy('date desc')->one();

        $continuation = 1;
        if ($sign) {
            if (!strcmp($sign->date, date('Y-m-d'))) {
                parent::throwError('签到失败!用户已签到');
            }
            $continuation = $sign->continuation + 1;
        }
        $userSignin = new UserSignin();
        $userSignin->user_id = $this->_token->user_id;
        $userSignin->date = date('Y-m-d');
        $userSignin->ipaddress = IpHelper::ip();
        $userSignin->continuation = $continuation;
        $userSignin->created_at = time();

        if (!$userSignin->save()) {
            parent::throwError('签到失败', $userSignin->getFirstErrors());
        }

        $credit = $this->addReward($continuation);

        $count = UserSignin::find()
            ->select("count(id)+1 as cnt")
            ->where(['date' => date('Y-m-d')])
            ->andWhere(['<=', 'created_at', $userSignin->created_at])
            ->andWhere(['<', 'id', $userSignin->id])
            ->asArray()
            ->one();

        $count['cnt'];

        return [
            'count' => $count['cnt'],
            'credit'=>$credit
        ];
    }

    /**
     * 签到奖励
     */
    public function addReward($continuation) {
        return [
            'gold'=>1,
            'orange'=>5,
            'orange_change'=>1,
            'exps'=>3,
            'exps_change'=>1,
        ];
    }


}
